package com.sam.im.heiqun.uis.activities;

import android.annotation.TargetApi;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.callmain.Maincallactivity;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.skyfishjy.library.RippleBackground;
import com.yuyh.library.view.image.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.SessionDescription;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.socket.client.Ack;
import io.socket.client.Socket;


public class AScallActivity extends AppCompatActivity  {

    @BindView(R.id.img_friend_icon)
    CircleImageView imgFriendIcon;
    @BindView(R.id.tv_invitation)
    TextView tvInvitation;
    @BindView(R.id.img_cancle)
    ImageView imgCancle;
    @BindView(R.id.img_as)
    ImageView imgAs;
    @BindView(R.id.content)
    RippleBackground content;
    @BindView(R.id.tv_name)
    TextView tvName;
    private Intent intent;
    private static Socket mSocket;
    private String destid;
    private String headurl;
    private MediaPlayer media;
    private static int START_LOCATION = 999;
    private String name;
    private boolean iscalling ;//是否执行过按钮操作
    private ImMessage getmsg ;
    /* private int firsttag = -1 ;
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // 需要做的事:发送消息
            Message message = new Message();
            message.what =START_LOCATION;
            myhandler.sendMessage(message);
        }
    };
    private Handler myhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 999 ://对方长时间无响应
                    if (firsttag!=-1){
                        ToolsUtils.showToast(AScallActivity.this,"长时间无应答，链接中断");
                        timer.cancel();
                        content.stopRippleAnimation();
                        if (media != null&&media.isPlaying()) {
                            media.stop();
                        }
                        finish();
                    }
                    firsttag++;
                    break;
            }
        }
    };
*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (media != null && media.isPlaying()) {
            media.stop();
        }
        if (!iscalling){
            setSocket();
            getmessage("0");
            content.stopRippleAnimation();
        }
        EventBus.getDefault().unregister(this);
        App.iscallvideoing = false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_ascall);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        intent = getIntent();
        App.iscallvideoing = true;
        destid = intent.getStringExtra("destid");
        headurl = intent.getStringExtra("headurl");
        name = intent.getStringExtra("name");
        getmsg = (ImMessage) intent.getSerializableExtra("immessage");
        if (headurl != null) {
            Glide.with(this).load(headurl).centerCrop().into(imgFriendIcon);
        }
        tvName.setText(name);
        content.startRippleAnimation();
        media = MediaPlayer.create(this, R.raw.phonering);
        media.setLooping(true);
        media.start();
        //setcallanswer();
        //timer.schedule(task,10,60000);
    }

    private void setcallanswer() {
        if (getmsg != null) {
            JSONObject contentjs = null;
            try {
                Log.i("info","==="+getmsg.getContent());
                contentjs = new JSONObject(getmsg.getContent());
                SessionDescription sdp = new SessionDescription(
                        SessionDescription.Type.fromCanonicalForm(contentjs.getString("type")),
                        contentjs.getString("sdp"));
                if (PeerConnectionFactory.initializeAndroidGlobals(
                        this,
                        true,
                        true,
                        true)) {
                    Toast.makeText(this, getResources().getString(R.string.init_success), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, getResources().getString(R.string.init_fail), Toast.LENGTH_SHORT).show();
                }
              /*  if (pc == null) {

                    //获取配置
                    LinkedList<PeerConnection.IceServer> iceServers = RtcUtil.getIceServers();
                    MediaConstraints pcConstraints = RtcUtil.getPcConstraints();
                    //初始化pc factory
                    App.pcFactory = new PeerConnectionFactory();
                    pc = App.pcFactory.createPeerConnection(iceServers, pcConstraints, new RtcConnObserver(this,this));
                }
                    pc.setRemoteDescription(observer, sdp);
                    pc.createAnswer(observer, RtcUtil.getPcConstraints());
                    //发送answer消息
                    JSONObject payload = new JSONObject();
                    payload.put("type", sdp.type.canonicalForm());
                    payload.put("sdp", sdp.description);
                    String sendSdp= payload.toString();
                    getmessage(sendSdp);*/
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void getCallMessage(ImMessage msg) {
        Log.i("info", "接收到的消息" + msg.toString());
        if (msg != null) {
            if (msg.getContent().equals("0")) {
                iscalling = true ;
                ToolsUtils.showToast(AScallActivity.this, getResources().getString(R.string.other_qx_call));
                finish();
            }
        }
    }

    @OnClick({R.id.img_cancle, R.id.img_as, R.id.content})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_cancle:
                iscalling = true ;
                setSocket();
                getmessage("0");
                if (media != null && media.isPlaying()) {
                    media.stop();
                }
                content.stopRippleAnimation();
                finish();
                break;
            case R.id.img_as:
                iscalling = true ;
                setSocket();
                if (media != null && media.isPlaying()) {
                    media.stop();
                }
                content.stopRippleAnimation();
                intent.setClass(this, Maincallactivity.class);
                intent.putExtra("type","21");
                intent.putExtra("immessage",getmsg);
               // getmessage("1");
                startActivity(intent);
                finish();
                break;
            case R.id.content:
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        // timer.cancel();
    }

    private void getmessage(String content) {
        long currentTime = System.currentTimeMillis();
        String fromid = ToolsUtils.getMyUserId();
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_CALLVIDEO, "1-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, Long.parseLong(destid), content, Constant.MESSAGE_TYPR_CALL_VIDEO_AS,
                currentTime, System.currentTimeMillis(), 0, "", fromid + "_" + destid, 0, ToolsUtils.getUser().getHeadUrl());
        socketSend(imMessage);
    }

    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub) {
        new Thread(new Runnable() {
            boolean sendState = false;
            int retryCount = 0;

            @Override
            public void run() {
                tbub.save();
                ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                socketSend(imMessage);
            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            private void socketSend(final ImMessage imMessage) {
                while (!sendState && retryCount < 10) {
                    mSocket = App.socket;
                    retryCount++;
                    if (mSocket != null) {
                        mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                            @Override
                            public void call(Object... args) {
                                imMessage.setSendState(Constant.COMPLETED);
                                tbub.setSendState(Constant.COMPLETED);
                                if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                                    imMessage.delete();
                                }
                                //sendMessageHandler.sendEmptyMessage(SEND_OK);
                                sendState = true;
                            }
                        });
                    }
                    try {
                        Thread.sleep(Constant.SOCKET_SEND_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    private void setSocket() {
        mSocket = App.socket;
        if (mSocket == null || !mSocket.connected()) {//mSocket 为空  这个基本不会出现 、或者链接断开了
            EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
            String savesocketstr = ToolsUtils.savesocketstr(this, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
        }
    }
}
